﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using HiddenFileManager.Properties;

namespace HiddenFileManager
{
    public partial class MainForm : Form
    {
        readonly Color TextBoxActiveColor = Color.FromArgb(255, 255, 255, 128);

        FileItemList _allItems;

        public MainForm()
        {
            InitializeComponent();

            try
            {
                _allItems = new FileItemList(ListFileName);
            }
            catch (Exception e)
            {
                // Delete the problematic file
                File.Delete(ListFileName);
                _allItems = new FileItemList(ListFileName);
            }

            // Initialize UI
            lbListOverlay.Bounds = lvItems.Bounds;
            lbListOverlay.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            _privacyMode = true;
            PrivacyMode = false;

            // Read stored values
            PrivacyMode = Settings.Default.PrivacyMode;

            // Status bar
            lbStatusAction.Visible = ShowHiddenFilesStatus;
            lbStatus.Text = Resources.statusDragToAdd;
        }

        String ListFileName
        {
            get
            {
                return
                    Path.Combine(Environment.GetFolderPath(
                        Environment.SpecialFolder.ApplicationData),
                        "HFM_TrackedItems.txt.enc");
            }
        }

        void FillItemList()
        {
            // Clear highlight if it was present
            tbFilter.BackColor = SystemColors.Window;

            this.lvItems.ItemChecked -= lvItems_ItemChecked;

            lvItems.Items.Clear();
            if (_allItems != null)
            {
                lbStatus.Text = String.Format(Resources.statusItemsTracked, _allItems.Count);
            }

            // No items
            String filter = Filter;
            if (_allItems != null && 
                filter != null) // null -- no items
            {
                // Filter
                lvItems.BeginUpdate();

                foreach (FileItem item in _allItems)
                {
                    if (filter == String.Empty || // all items 
                        item.Matches(Filter))
                    {
                        lvItems.Items.Add(item);
                    }
                }
                lvItems.EndUpdate();
            }

            UpdateOverlayLabel();

            this.lvItems.ItemChecked += lvItems_ItemChecked;
        }

        void UpdateOverlayLabel()
        {
            if (lvItems.Items.Count == 0)
            {
                if (_allItems == null || _allItems.Count == 0)
                {
                    lbListOverlay.Text = Resources.overlayDragItems;
                }
                else 
                {
                    lbListOverlay.Text = PrivacyMode ?
                        Resources.overlayPrivacyMode :
                        Resources.overlayNoItemsFound;
                }
                lbListOverlay.Visible = true;
            }
            else
            {
                lbListOverlay.Visible = false;
            }
        }


        private void cbPrivacyMode_CheckedChanged(object sender, EventArgs e)
        {
            PrivacyMode = cbPrivacyMode.Checked;
            Settings.Default.PrivacyMode = PrivacyMode;
            Settings.Default.Save();
        }

        bool _privacyMode = false;
        bool PrivacyMode
        {
            get { return _privacyMode; }
            set
            {
                if (value == _privacyMode) { return; }

                _privacyMode = value;
                if (cbPrivacyMode.Checked != _privacyMode)
                {
                    cbPrivacyMode.Checked = _privacyMode;                    
                }

                SuspendLayout();

                // TODO: preserve when going OUT of privacy mode
                if (_privacyMode)
                {
                    Text = Resources.titlePrivacyMode;

                    pTopBar.BackColor = Color.Silver;
                    pbSpy.Visible = true;
                    bShow.Visible = true;
                    tbFilter.Width -= bShow.Width;

                    // Clear the filter, for privacy
                    tbFilter.Text = "";

                    FillItemList();

                    tbFilter.BackColor = TextBoxActiveColor;
                    tbFilter.Select();
                }
                else
                {
                    Text = Resources.titleNormal;

                    pTopBar.BackColor = SystemColors.Control;
                    pbSpy.Visible = false;
                    bShow.Visible = false;
                    tbFilter.BackColor = Color.White;
                    tbFilter.Width += bShow.Width;

                    FillItemList();
                }

                ResumeLayout();
            }
        }

        private void bShow_Click(object sender, EventArgs e)
        {
            FillItemList();
        }

        private void lvItems_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && 
                e.X > 16) // Prevents revert on checkbox itself
            {
                // Switch selected items depending on the first one

                if (lvItems.SelectedItems.Count > 0)
                {
                    bool state = !lvItems.SelectedItems[0].Checked;
                    foreach(FileItem item in lvItems.SelectedItems)
                    {
                        item.Checked = state;
                    }
                }

                /*
                FileItem item = lvItems.GetItemAt(e.X, e.Y) as FileItem;
                if (item != null)
                {
                    item.Checked = !item.Checked;
                }
                 */
            }
        }

        private void lvItems_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            FileItem fsi = e.Item as FileItem;
            if (fsi == null) { return; }
            if (fsi.Status != ItemStatus.Visible && fsi.Status != ItemStatus.Hidden) { return; }
            
            fsi.SetHidden(e.Item.Checked);            
        }

        private void tbFilter_TextChanged(object sender, EventArgs e)
        {
            if (PrivacyMode)
            {
                tbFilter.BackColor = TextBoxActiveColor;
            }
            else
            {
                FillItemList();
            }
        }

        private void tbFilter_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                FillItemList();
            }
        }

        public String Filter
        {
            get
            {
                if (String.IsNullOrEmpty(tbFilter.Text))
                {
                    if (PrivacyMode) { return null; } // no items
                    else { return String.Empty; } // all items
                }
                return tbFilter.Text;
            }
        }

        private void lvItems_DragDrop(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent("FileDrop")) { return; }

            String[] files = e.Data.GetData("FileDrop", true) as String[];
            _allItems.AddItems(files);
            FillItemList();
        }

        private void lvItems_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("FileDrop"))
            {
                e.Effect = DragDropEffects.Link;
            }
            else 
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void lvItems_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (lvItems.SelectedItems.Count > 0)
                {
                    int selectedIndex = lvItems.SelectedIndices[0];
                    lvItems.BeginUpdate();
                    foreach (FileItem item in lvItems.SelectedItems)
                    {
                        lvItems.Items.Remove(item);
                        _allItems.Remove(item);
                    }
                    lvItems.EndUpdate();

                    if (lvItems.Items.Count > 0)
                    {
                        if (selectedIndex >= lvItems.Items.Count) { selectedIndex = lvItems.Items.Count - 1; }
                        lvItems.SelectedIndices.Add(selectedIndex);
                    }

                    _allItems.Save();

                    UpdateOverlayLabel();
                }
            }
        }

        private void bHideAll_Click(object sender, EventArgs e)
        {
            lvItems.BeginUpdate();
            foreach (FileItem fi in _allItems)
            {
                fi.SetHidden(true);
            }
            lvItems.EndUpdate();
        }

        private void bUnhideAll_Click(object sender, EventArgs e)
        {
            lvItems.BeginUpdate();
            foreach (FileItem fi in _allItems)
            {
                fi.SetHidden(false);
            }
            lvItems.EndUpdate();
        }

        public static bool ShowHiddenFilesStatus
        {
            get
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"))
                {
                    return (int)key.GetValue("Hidden") == 1;
                }
            }
        }

        private void lbStatusAction_Click(object sender, EventArgs e)
        {
            if (ShowHiddenFilesStatus)
            {
                MessageBox.Show(this,
                    "Hidden items are shown in Windows Explorer. \r\n" +
                    "\r\n" +
                    "To make them invisible: \r\n" +
                    "1) Open any Explorer window \r\n" +
                    "2) Open the menus (press Alt if not visible) \r\n" +
                    "3) Select Tools >> Folder Options \r\n" +
                    "4) Switch to View tab and click \r\n" +
                    "   \"Don't show hidden files, folders, or drives\"\r\n" +
                    "5) Click OK or Apply",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            lbStatusAction.Visible = ShowHiddenFilesStatus;
        }

    }



}
